package com.sovphone.clevertools

import android.Manifest
import android.app.Activity
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.app.TimePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.math.log


class MainActivity : AppCompatActivity() {

    private var units = arrayOf<String>()
    private var unitStr = "秒"
    private var dateStr = ""
    private var timeStr = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        units = resources.getStringArray(R.array.unit)
        unitStr = units[0]
        open.setOnClickListener {
            if (TextUtils.isEmpty(dateStr) || TextUtils.isEmpty(timeStr)) {
                Toast.makeText(this@MainActivity, "请选择打卡日期", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (TextUtils.isEmpty(comp.text.toString().trim())) {
                Toast.makeText(this@MainActivity, "请输入公司名称(钉钉首页底部中间按钮的名称)", Toast.LENGTH_SHORT)
                    .show()
                return@setOnClickListener
            }
            val time =
                DateUtils.parse("$dateStr $timeStr")
            val intervalTime = repeat.value * getUnitTime()
            var msg = "任务已启动"
            if (time <= System.currentTimeMillis()) {
                msg = "请更正打卡时间"
            } else {
                CleverService.getInstance()?.start(time, intervalTime, comp.text.toString().trim())
                date.text =
                    "${comp.text.toString().trim()}\n打卡时间：${DateUtils.format(
                        time
                    )}\n${if (intervalTime > 0) "每隔${repeat.value}${unitStr}打卡" else "不重复"}"
            }
            Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
        }
        dateBtn.setOnClickListener {
            showDatePickDlg()
        }

        timeBtn.setOnClickListener {
            showTimePickDlg()
        }

        setRepeatPicker()
        setUnit()
        requestPermissions(
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), 200
        )
    }

    fun getUnitTime(): Long {
        return when (unitStr) {
            "天" -> 24 * 60 * 60 * 1000L
            "时" -> 60 * 60 * 1000L
            "分" -> 60 * 1000L
            "秒" -> 1000L
            else -> 0
        }
    }

    fun setRepeatPicker() {
        repeat.maxValue = 60
        repeat.minValue = 0
        repeat.setOnValueChangedListener { picker, oldVal, newVal ->

        }
    }

    fun setUnit() {
        unit.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                unitStr = units[position]
            }

        }
    }

    fun showDatePickDlg() {
        val calendar: Calendar = Calendar.getInstance()
        val datePickerDialog = DatePickerDialog(
            this,
            OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                dateStr = "$year-${monthOfYear + 1}-$dayOfMonth"
                dateBtn.text = dateStr
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        datePickerDialog.show()
    }

    fun showTimePickDlg() {
        val calendar: Calendar = Calendar.getInstance()
        val datePickerDialog = TimePickerDialog(
            this,
            TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
                timeStr = "$hourOfDay:$minute"
                timeBtn.text = timeStr
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE), true
        )
        datePickerDialog.show()
    }

    override fun onResume() {
        super.onResume()
        //全局弹窗
//        checkDialogPermission()
        checkAccess()
    }

    var dialog: AlertDialog? = null
    private fun checkAccess() {
        Log.e("Main", "checkAccess")
        if (Build.VERSION_CODES.N <= Build.VERSION.SDK_INT && CleverService.getInstance() == null && (dialog == null || !dialog!!.isShowing)) {
            dialog = AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("应用功能需要获取无障碍权限，请设置")
                .setPositiveButton("去设置") { dialog, which ->
                    if (CleverService.getInstance() == null) {
                        val intentAccess =
                            Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
                        startActivityForResult(
                            intentAccess,
                            Constants.REQUEST_CODE_ACCESS_PERMISSION
                        )
                    }
                    dialog.dismiss()
                }.create();
            dialog?.setCancelable(false)
            dialog?.setCanceledOnTouchOutside(false)
            dialog?.show()
        } else {

        }
    }

    private fun checkDialogPermission() {
        if (Build.VERSION_CODES.M <= Build.VERSION.SDK_INT && !Settings.canDrawOverlays(this)) {
            val dialog = AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("应用功能需要获取弹窗权限，请设置")
                .setPositiveButton("去设置") { dialog, which -> //启动Activity让用户授权
                    val intent = Intent(
                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:$packageName")
                    )
                    startActivityForResult(intent, Constants.REQUEST_CODE_OVERLAY_PERMISSION)
                    dialog.dismiss()
                }.create();
            dialog.setMessage("应用功能需要获取弹窗权限，请设置")
            dialog.setCancelable(false)
            dialog.setCanceledOnTouchOutside(false)
            dialog.show()
        } else {
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 200) {
            var granted = true
            for (i in grantResults) {
                if (i != PackageManager.PERMISSION_GRANTED) {
                    granted = false
                    break
                }
            }
            if (granted) {
                //无障碍
                checkAccess()
            } else {
                finish()
            }
        }
    }
}